package com.hdu.careerplan.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONWriter;
import com.hdu.careerplan.enums.StatusCode;
import com.hdu.careerplan.exception.WrongKeyInJwtException;
import com.hdu.careerplan.pojo.vo.Result;
import com.hdu.careerplan.pojo.vo.ResultData;
import com.hdu.careerplan.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = {"/assessment/*", "/data_analysis*","/recommend/*","/user/*"})
public class UserFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            System.out.println("Method:OPTIONS");
            String allowOrigin = request.getHeader("Origin");
            String allowHeader = request.getHeader("Access-Control-Request-Headers");
            System.out.println(allowOrigin);
            System.out.println(allowHeader);
            response.setHeader("Access-Control-Allow-Origin", allowOrigin);
            //设置允许带cookie的请求
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "OPTIONS, POST, PUT, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Headers", allowHeader);
            return;
        }

        //1.获取请求url
        String url = request.getRequestURL().toString();
        log.info("url:{}", url);

        //2.判断是否是登录请求
        if (url.contains("login") || url.contains("register")) {
            log.info("登录/注册操作放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3.判断是否携带token
        String jwt = request.getHeader("token");
        System.out.println(jwt);
        if (jwt == null) {
            log.info("未携带token，请求被拦截");
            response.setStatus(401);
            ResultData error = Result.responseWithNonData(StatusCode.NOT_LOGIN);
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        //4.解析jwt
        try {
            JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            log.info("token解析失败，请求被拦截");
            response.setStatus(401);
            ResultData error = Result.responseWithNonData(StatusCode.ILLEGAL_TOKEN);
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        // 5
        try {
            JwtUtil.getInfoFromJWT(servletRequest, "userId");
        } catch (WrongKeyInJwtException wrongKeyInJwtException) {
            wrongKeyInJwtException.printWrongKey();
            log.info("人员身份不对，应为用户，实际为工作人员");
            response.setStatus(401);
            ResultData error = Result.responseWithNonData(StatusCode.WRONG_IDENTITY);
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }

        //5.放行
        log.info("UserFilter合法放行");
        filterChain.doFilter(servletRequest, servletResponse);



    }
}
